package cn.shiwei.org.service.impl;

import cn.shiwei.basic.constants.UserConstants;
import cn.shiwei.basic.service.impl.BaseServiceImpl;
import cn.shiwei.basic.util.MD5Utils;
import cn.shiwei.basic.util.StrUtils;
import cn.shiwei.org.domain.Employee;
import cn.shiwei.org.domain.Shop;
import cn.shiwei.org.mapper.EmployeeMapper;
import cn.shiwei.org.mapper.ShopMapper;
import cn.shiwei.org.service.IShopService;
import cn.shiwei.user.domain.Logininfo;
import cn.shiwei.user.mapper.LogininfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    @Transactional
    public void save(Shop shop) {
        Employee admin = shop.getAdmin();
        System.out.println("注册接收密码" + admin.getPassword());
        /* 条件判断, 排除两次密码不一致 */
        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new RuntimeException("密码不一致");
        }
        /* 条件拍段排除账号, 邮箱, 电话重复 */
        Employee emp = employeeMapper.loadByAdmin(admin);
        if (emp != null) {
            throw new RuntimeException("账号名/邮箱/手机号, 重复注册");
        }

        // 保存员工信息, 返回主键
        employeeMapper.save(admin);
        // 保存店铺信息,  保存店主外键 ,返回主键
        shopMapper.save(shop);

        // 将主键录入员工表
        admin.setShop(new Shop());
        admin.getShop().setId(shop.getId());

        Logininfo logininfo = new Logininfo(admin.getUsername(), admin.getPassword(), UserConstants.ADMIN_TYPE);
        logininfoMapper.save(logininfo);
        admin.setSalt(logininfo.getSalt());
        admin.setPassword(logininfo.getPassword());
        // 将登录id录入员工表
        admin.setLogininfo(logininfo);

        // 更新员工表, 保存店主外键
        employeeMapper.update(admin);
        System.out.println("员工表密码" + admin.getPassword());
    }
}
